<template>
  <div id="self_defined_element" class="self-defined-classname"></div>
</template>

<script>

import dingtalk from "@/utils/dingtalk"
export default {
  mounted() {
    dingtalk.DTFrameLogin(
      {
        id: 'self_defined_element',
        width: 250,
        height: 250,
      },
      {
        redirect_uri: encodeURIComponent(window.location.href),
        client_id: 'dingfamesyeg8x66uwng',
        scope: 'openid',
        response_type: 'code',
        state: 'state',
        prompt: 'consent',
      },
      (loginResult) => {
        const { authCode } = loginResult;
        this.dingtalkLogin(authCode, authCode);
      },
      (errorMsg) => {
        // 这里一般需要展示登录失败的具体原因
        alert(`Login Error: ${errorMsg}`);
      },
    );
  },
  methods: {
    // get os
    GetOs() {

      return 'others'
    }
    ,
    async dingtalkLogin(code, authCode) {
      var user = await this.$API.auth.DingTalkAuth.post({ code: code, authCode: authCode });
      await this.setLoginData(user);
    },
    async setLoginData(user) {
      //设置用户前，判断版本
      let VERSION = this.$TOOL.data.get("VERSION");
      let NEW_VERSION = await this.getVer();
      if (VERSION != NEW_VERSION) {
        this.$TOOL.data.clear();
        this.$TOOL.data.set("VERSION", NEW_VERSION);
      }
      if (user.code == 200) {
        this.$TOOL.data.set(
          "TOKEN",
          user.data.token,
          24 * 60 * 60
        );

        this.$TOOL.data.set("USER_INFO", user.data.userInfo);
        this.$TOOL.data.set("LOGIN_COUNT", user.data.count);
      } else {
        this.$message.warning(user.message);
        return false;
      }
      //获取菜单
      var menu = null;
      // if (this.form.user == "admin") {
      menu = await this.$API.system.menu.myMenus.get();
      // } else {
      //   menu = await this.$API.demo.menu.get();
      // }
      if (menu.code == 200) {
        if (menu.data.length == 0) {
          this.$alert("当前用户无任何菜单权限，请联系系统管理员", "无权限访问", {
            type: "error",
            center: true,
          });
          return false;
        }
        this.$TOOL.data.set("MENU", menu.data);
        // this.$TOOL.data.set("PERMISSIONS", menu.data.permissions);
      } else {
        this.$message.warning(menu.message);
        return false;
      }
      this.$WS.connection();
      this.$message.success("Login Success 登录成功");
      this.$router.replace({
        path: "/",
      });
    },
    async getVer() {
      const ver = await this.$API.system.version.get()
      return ver.data;
    },
  },
};
</script>

<style></style>
